package com.qf.websocketdemo.websocket;

import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Scanner;

@Component
@ServerEndpoint("/websocket")
public class WebSocketServert {

    /**
     * 当浏览器建立websokce连接时，会调用如下方法
     * Session 对象，代表了与浏览器端已经建立好的 websocket 连接
     */
    @OnOpen
    public void open(Session session) throws IOException {

        System.out.println(session);
//        session.getBasicRemote().sendText("hello from sever");

        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {

                while (true){
                    // 接收控制台的输入
                    final Scanner scanner = new Scanner(System.in);
                    final String line = scanner.next();

                    // 将消息写回给浏览器端的websocket对象
                    session.getBasicRemote().sendText(line);
                }

            }
        }).start();

    }

    /**
     * 服务器端接口收websocket消息
     * @param msg
     * @param session
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String msg,Session session) throws IOException {
        System.out.println("浏览器发来了消息:"+msg);
        session.getBasicRemote().sendText("from server:"+msg);
    }


    /**
     * 关闭连接时会调用下面的方法
     */
    @OnClose
    public void onClose(Session session) throws IOException {

        System.out.println("浏览器要断开连接啦，要断开的服务器端的session是:"+session);
        session.close();  // 关闭掉session对象

    }

}
